<?php

namespace app\api\controller\user;

use app\common\controller\Api;
use think\Db;


class Cart extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 购物车列表
     * @ApiMethod (GET)
     * @path api/user/cart/index
     */
    public function index()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $totalAmount = 0;//总金额
        $goodsIdArr = [];
        $cartId = $this->request->get('cart_id');
        $selectedcartId = isset($cartId) && !empty($cartId) ? $cartId : "";//选中的购物车商品
        $selectedcartId = explode(',',$selectedcartId);
        $goodsLike = [];
        $cart = db('cart')
            ->field('a.id,a.goods_id,b.image,b.goods_name,b.spec_name,b.price,a.num,a.is_delete,a.user_del')
            ->alias('a')
            ->join('goods b','a.goods_id = b.id','LEFT')
            ->where([
                'a.user_id'=>$userId,
                'a.store_id'=>$storeId,
                'a.is_delete'=>'0',
                'a.user_del'=>'0',
                'b.is_on_sale'=>'1',
            ])->select();
        $cart = goodsPriceReset($cart,$this->auth->type,'goods_id');
        $cart = addWebSiteUrl($cart,['image']);
        foreach ($cart AS $key1 => $value1) {
            $cart[$key1]['selected'] = false;
            if (in_array($value1['id'],$selectedcartId)) {
                $cart[$key1]['selected'] = true;
                $totalAmount+=bcmul($value1['price'],$value1['num'],2);
            }
            $goodsIdArr[] = $value1['goods_id'];
            //追加库存
            $stock = db('store_goods')->where(['store_id'=>$storeId,'goods_id'=>$value1['goods_id']])->value('stock');
            $cart[$key1]['kucun'] = $stock;
        }

        //猜你喜欢
        $order = db('order')->where([
            'user_id'=>$userId,
            'order_type'=>1
        ])->select();

   
        $goodsIdStr = implode(',',$goodsIdArr);
        if (empty($order)) {
            $goodsLike = db('goods')->where([
                'index_status'=>1,
                'is_on_sale'=>1
            ])->where('id','not in',$goodsIdStr)->limit(0,3)->select();
        } else {
     
            $goodsIdArr = [];
            $cateIdArr = [];
            foreach ($order AS $key => $value) {
                $orderGoods = db('order_goods')->where('order_id',$value['id'])->select();
                foreach ($orderGoods AS $key1 => $value1) {
                    $goodsIdArr[] = $value1['goods_id'];
                }
            }
            $goods = db('goods')->where('id','in',$goodsIdArr)->select();
            foreach ($goods AS $kkk => $vvv) {
                $cateIdArr[] = $vvv['cate_id'];
            }
            $cateIdStr = implode(',',$cateIdArr);
            $goodsLike = db('goods')->where('cate_id','in',$cateIdStr)->where('id','not in',$goodsIdStr)->where('is_on_sale',1)->limit(0,3)->select();
        }
    
        $goodsLike = goodsPriceReset($goodsLike,$this->auth->type);
        $goodsLike = addWebSiteUrl($goodsLike,['image']);

        $notGoods = db('store')->where('id',$storeId)->value('not_goods');
        $notGoods = explode(',',$notGoods);
        foreach ($goodsLike AS $kk => $vv) {
            if (in_array($vv['id'],$notGoods)) {
                unset($goodsLike[$kk]);
            }
        }


        $backList = [
            'count'=>count($cart),
            'cartList'=>$cart,
            'wantLike'=>$goodsLike,
            'totalAmount'=>$totalAmount,
        ];
        $this->success('操作成功',$backList);
    }

    /**
     * 加入购物车
     * @ApiMethod (POST)
     * @path api/user/cart/add
     */
    public function add()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $goodsId = $this->request->param('goods_id');
        $num = $this->request->param('num',1);

        $isRel = db('cart')->where([
            'user_id'=>$userId,
            'goods_id'=>$goodsId,
            'store_id'=>$storeId,
            'user_del'=>'0',
            'is_delete'=>0
        ])->find();
        if (empty($isRel)) {
            db('cart')->insert([
                'user_id'=>$userId,
                'goods_id'=>$goodsId,
                'num'=>$num,
                'store_id'=>$storeId,
                'addtime'=>date('Y-m-d H:i:s')
            ]);
        } else {
            db('cart')->where([
                'user_id'=>$userId,
                'goods_id'=>$goodsId,
                'store_id'=>$storeId,
            ])->setInc('num',$num);
        }

        $this->success('加入成功');
    }

    /**
     * 修改购物车商品数量
     * @ApiMethod (POST)
     * @path api/user/cart/edit
     */
    public function edit()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $cartId = $this->request->param('cart_id');
        $num = $this->request->param('num',1);
        db('cart')->where([
            'user_id'=>$userId,
            'id'=>$cartId,
            'store_id'=>$storeId,
            'user_del'=>'0'
        ])->update([
            'num'=>$num,
        ]);
        $this->success('修改成功');
    }


    /**
     * 删除购物车商品
     * @ApiMethod (POST)
     * @path api/user/cart/delete
     */
    public function delete()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $cartId = $this->request->post('cart_id');
        if (!isset($cartId) || empty($cartId)) {
            $this->error('请选择移出购物车的商品');
        }
        db('cart')->where(['user_id'=>$userId,'store_id'=>$storeId])->where('id','in',$cartId)->delete();
        $this->success('删除成功');
    }

    /**
     * 购物车结算页面
     * @ApiMethod (GET)
     * @path api/user/cart/settlement
     */
    public function settlement()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;
        $type = $this->request->param('type',1);//1快递邮寄   2到店自提
        $cartId = $this->request->param('cart_id');
        if (empty($cartId)) {
            $this->error('未获取到选中产品信息');
        }
        $todayDay = date('Y-m-d H:i:s');
        $totalAmount = 0;//总金额
        $goodsTotalNum = 0;//总数量
        $manJian = [];//满减信息


            //快递邮寄
            $address = db('address')->where(['user_id'=>$userId,'is_default'=>1])->find();
            if (!empty($address)) {
                $province = db('area')->where('id',$address['province'])->value('name');
                $city = db('area')->where('id',$address['city'])->value('name');
                $area = db('area')->where('id',$address['area'])->value('name');
                $address['province_name'] = $province;
                $address['city_name'] = $city;
                $address['area_name'] = $area;
            }

            //到店自提
            $addressInfo = db('address')->where(['user_id'=>$userId,'is_default'=>1])->find();
            $store = db('store')->where('id',$storeId)->find();
            $province1 = db('area')->where('id',$store['province'])->value('name');
            $city1 = db('area')->where('id',$store['city'])->value('name');
            $area1 = db('area')->where('id',$store['area'])->value('name');
            $store['province_name'] = $province1;
            $store['city_name'] = $city1;
            $store['area_name'] = $area1;
            $address1 = [
                'store_name'=>$store['store_name'],
                'store_phone'=>$store['tel'],
                'province_name'=>$province1,
                'city'=>$city1,
                'area'=>$area1,
                'address'=>$store['address'],
                'business_start_time'=>$store['business_start_time'],
                'business_end_time'=>$store['business_end_time'],
                'name' => '',
                'tel' => ''
            ];
            if (!empty($addressInfo)) {
                $address1['name'] = $addressInfo['name'];
                $address1['tel'] = $addressInfo['tel'];
            }


        $cart = db('cart')
            ->field('a.id,a.goods_id,b.image,b.goods_name,b.spec_name,b.price,a.num')
            ->alias('a')
            ->join('goods b','a.goods_id = b.id')
            ->where([
                'a.user_id'=>$userId,
                'a.store_id'=>$storeId,
            ])
            ->where('a.id','in',$cartId)
            ->select();
        $cart = goodsPriceReset($cart,$this->auth->type,'goods_id');
        $cart = addWebSiteUrl($cart,['image']);
        foreach ($cart AS $key => $value) {

            $totalAmount= bcadd($totalAmount,bcmul($value['price'],$value['num'],2),2);

            $goodsTotalNum+=$value['num'];
        }

        $isManJian = true;//默认开启满减

        $highuserManjian = db('config')->where(['name'=>'highuser_manjian','group'=>'basic'])->value('value');
        $partnerManjian = db('config')->where(['name'=>'partner_manjian','group'=>'basic'])->value('value');
        $user = db('user')->where('id',$userId)->find();
        if ($user['type'] == 2 && $highuserManjian == 0) {
            //高级用户
            $isManJian = false;
        }
        if ($user['type'] == 3 && $partnerManjian == 0) {
            //合伙人
            $isManJian = false;
        }

        if ($isManJian == true) {
            //满减活动
            $active = db('store_active')
                ->where([
                'store_id'=>$storeId,
                'status'=>1,
                'authen'=>2
            ])->where("starttime<='{$todayDay}' and endtime > '{$todayDay}'")
                ->order('minus_price DESC')
                ->select();
            foreach ($active AS $kk => $vv) {
                if ($totalAmount >= $vv['full_price']) {
                    $manJian = $vv;
                    break;
                }
            }
            
            if (!empty($manJian)) {
                unset($manJian['store_id']);
                unset($manJian['authen']);
                unset($manJian['updatetime']);
                unset($manJian['remark']);
                unset($manJian['authen_time']);
                unset($manJian['status']);
            }
        }
        
    
        $manJianPrice = isset($manJian['minus_price']) ? $manJian['minus_price'] : 0;
        $backList = [
            'address'=>$address,
            'address1'=>$address1,
            'cart'=>$cart,
            'totalAmount'=>$totalAmount,
            'manJian'=>$manJian,
            'heji'=>bcsub($totalAmount,$manJianPrice,2),
            'goodsTotalNum'=>$goodsTotalNum
        ];

        $this->success('操作成功',$backList);
    }

    /**
     * 立即购买结算页面
     * @ApiMethod (GET)
     * @path api/user/cart/settlementQuick
     */
    public function settlementQuick()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;
        $type = $this->request->param('type',1);//1快递邮寄   2到店自提
        $goodsId = $this->request->param('goods_id');
        $num = $this->request->param('num',1);
        if (empty($goodsId)) {
            $this->error('未获取到选中产品信息');
        }
        $todayDay = date('Y-m-d H:i:s');
        $totalAmount = 0;//总金额
        $manJian = [];//满减信息

        //快递邮寄
        $address = db('address')->where(['user_id'=>$userId,'is_default'=>1])->find();
        if (!empty($address)) {
            $province = db('area')->where('id',$address['province'])->value('name');
            $city = db('area')->where('id',$address['city'])->value('name');
            $area = db('area')->where('id',$address['area'])->value('name');
            $address['province_name'] = $province;
            $address['city_name'] = $city;
            $address['area_name'] = $area;
        }

        //到店自提
        $addressInfo = db('address')->where(['user_id'=>$userId,'is_default'=>1])->find();
        $store = db('store')->where('id',$storeId)->find();
        $province1 = db('area')->where('id',$store['province'])->value('name');
        $city1 = db('area')->where('id',$store['city'])->value('name');
        $area1 = db('area')->where('id',$store['area'])->value('name');
        $store['province_name'] = $province1;
        $store['city_name'] = $city1;
        $store['area_name'] = $area1;
        $address1 = [
            'store_name'=>$store['store_name'],
            'store_phone'=>$store['tel'],
            'province_name'=>$province1,
            'city'=>$city1,
            'area'=>$area1,
            'address'=>$store['address'],
            'business_start_time'=>$store['business_start_time'],
            'business_end_time'=>$store['business_end_time'],
            'name' => '',
            'tel' => ''
        ];
        if (!empty($addressInfo)) {
            $address1['name'] = $addressInfo['name'];
            $address1['tel'] = $addressInfo['tel'];
        }


        $goods = db('goods')->where('id','in',$goodsId)->select();
        $goods = goodsPriceReset($goods,$this->auth->type);
        $goods = addWebSiteUrl($goods,['image','goods_images']);
        foreach ($goods AS $key => $value) {

            $totalAmount=bcadd($totalAmount,bcmul($value['price'],$num,2),2);
            $goods[$key]['num'] = $num;
        }

        $isManJian = true;//默认开启满减

        $highuserManjian = db('config')->where(['name'=>'highuser_manjian','group'=>'basic'])->value('value');
        $partnerManjian = db('config')->where(['name'=>'partner_manjian','group'=>'basic'])->value('value');
        $user = db('user')->where('id',$userId)->find();
        if ($user['type'] == 2 && $highuserManjian == 0) {
            //高级用户
            $isManJian = false;
        }
        if ($user['type'] == 3 && $partnerManjian == 0) {
            //合伙人
            $isManJian = false;
        }
        if ($isManJian == true) {
            //满减活动
            $active = db('store_active')
                ->where([
                    'store_id'=>$storeId,
                    'status'=>1,
                    'authen'=>2
                ])->where("starttime<='{$todayDay}' and endtime > '{$todayDay}'")
                ->order('minus_price DESC')
                ->select();
            foreach ($active AS $kk => $vv) {
                if ($totalAmount >= $vv['full_price']) {
                    $manJian = $vv;
                    break;
                }
            }
            unset($manJian['store_id']);
            unset($manJian['authen']);
            unset($manJian['updatetime']);
            unset($manJian['remark']);
            unset($manJian['authen_time']);
            unset($manJian['status']);
        }
        
        $manJianPrice = isset($manJian['minus_price']) ? $manJian['minus_price'] : 0;
        $backList = [
            'address'=>$address,
            'address1'=>$address1,
            'cart'=>$goods,
            'totalAmount'=>$totalAmount,
            'manJian'=>$manJian,
            'heji'=>bcsub($totalAmount,$manJianPrice,2),
        ];

        $this->success('操作成功',$backList);
    }

}
